package com.guchenbo.example.serialize;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class Hessian2Serializer {
    public static byte[] serialize(Object obj) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream);

        hessianOutput.writeObject(obj);
        hessianOutput.close();

        return byteArrayOutputStream.toByteArray();
    }

    public static <T> T deserialize(byte[] data, Class<T> type) throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        HessianInput hessianInput = new HessianInput(byteArrayInputStream);

        T result = (T) hessianInput.readObject(type);
        hessianInput.close();

        return result;
    }
}
